package config

import (
	"log"
	"os"
	"time"

	"github.com/joho/godotenv"
)

type Config struct {
	Server   ServerConfig
	Database DatabaseConfig
	Redis    RedisConfig
	JWT      JWTConfig
	Mock     MockConfig
}

type ServerConfig struct {
	Port string
	Mode string
}

type DatabaseConfig struct {
	Type     string // sqlite, postgres, mysql
	Host     string
	Port     string
	User     string
	Password string
	DBName   string
	SSLMode  string
	FilePath string // 用于SQLite
}

type RedisConfig struct {
	Enabled  bool
	Host     string
	Port     string
	Password string
	DB       int
}

type JWTConfig struct {
	Secret string
	Expire time.Duration
}

// MockConfig 模拟配置，用于开发环境
type MockConfig struct {
	UseMockDB    bool // 是否使用模拟数据库
	UseMockRedis bool // 是否使用模拟Redis
}

var AppConfig *Config

func Init() {
	// 加载环境变量
	if err := godotenv.Load(); err != nil {
		log.Println("未找到.env文件，使用系统环境变量")
	}

	// 检查是否使用模拟模式
	useMockDB := getEnvBool("USE_MOCK_DB", true)
	useMockRedis := getEnvBool("USE_MOCK_REDIS", true)

	AppConfig = &Config{
		Server: ServerConfig{
			Port: getEnv("SERVER_PORT", "8080"),
			Mode: getEnv("SERVER_MODE", "debug"),
		},
		Database: DatabaseConfig{
			Type:     getEnv("DB_TYPE", "sqlite"),
			Host:     getEnv("DB_HOST", "localhost"),
			Port:     getEnv("DB_PORT", "5432"),
			User:     getEnv("DB_USER", "postgres"),
			Password: getEnv("DB_PASSWORD", "postgres"),
			DBName:   getEnv("DB_NAME", "admin_system"),
			SSLMode:  getEnv("DB_SSLMODE", "disable"),
			FilePath: getEnv("DB_FILE_PATH", "admin-system.db"),
		},
		Redis: RedisConfig{
			Enabled:  !useMockRedis,
			Host:     getEnv("REDIS_HOST", "localhost"),
			Port:     getEnv("REDIS_PORT", "6379"),
			Password: getEnv("REDIS_PASSWORD", ""),
			DB:       0,
		},
		JWT: JWTConfig{
			Secret: getEnv("JWT_SECRET", "your_jwt_secret_key"),
			Expire: parseDuration(getEnv("JWT_EXPIRE", "24h")),
		},
		Mock: MockConfig{
			UseMockDB:    useMockDB,
			UseMockRedis: useMockRedis,
		},
	}
}

func getEnv(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}

func getEnvBool(key string, defaultValue bool) bool {
	if value := os.Getenv(key); value != "" {
		return value == "true" || value == "1"
	}
	return defaultValue
}

func parseDuration(s string) time.Duration {
	duration, err := time.ParseDuration(s)
	if err != nil {
		log.Printf("解析时间失败: %v, 使用默认值24h", err)
		return 24 * time.Hour
	}
	return duration
}
